<template>
    <div class="flex h-screen">
        <el-container>
            <!-- 左侧边栏 -->
            <el-aside class="left-aside">
                <el-button class="new-chat-btn" @click="newChat">新对话</el-button>
                <div v-for="(chat, index) in chats" :key="index" class="chat-list" @click="selectChat(index)">
                    {{ chat.name }}
                </div>
            </el-aside>
            
            <!-- 右侧聊天区域 -->
            <el-main class="right-main">
                <div class="flex-1 overflow-y-auto border p-4 bg-white">
                    <div v-for="(msg, idx) in currentChat.messages" :key="idx" class="mb-2">
                        <div class="messag-cent">
                            <div class="messag-cent-left"> 
                                <!-- <div>{{ msg.userLeft }}</div> -->
                                <!-- <div class="msg">{{ msg.textLeft }}</div> -->
                                <div class="msg" v-html="renderedMarkdownTest(msg.textLeft)"></div>
                            </div>
                            <div class="messag-cent-right"> 
                                <div>{{ msg.userRight }}</div>
                            <div>{{msg.textRight}}</div>
                            </div>                           
                        </div>
                    </div>
                </div>
                
                <div class="send-message-div">
                    <el-input v-model="newMessage" placeholder="请输入内容" @keyup.enter="sendMessage"></el-input>
                    <el-button type="primary" round @click="sendMessage">发送</el-button>
                </div>
            </el-main>
        </el-container>
    </div>
</template>
  
<script>
import { marked } from 'marked';

  export default {
    data() {
      return {
        chats: [{ name: "对话 1", messages: [{ userLeft:"",
            textLeft: "你好，有什么可以帮你的吗？", 
            textRight: "",
            userRight:"",
            msgType: "left"}]}],
        currentIndex: 0,
        newMessage: "",
        dsMsg: {
            id:"",
            choices: [{
                delta:{
                    content:"",
                    role:"",
                    reasoning_content:""
                },
                index:""
            }],
            created:1,
            model:"",
            object:""
        }
      };
    },
    computed: {
        currentChat() {
            return this.chats[this.currentIndex] || { messages: [] };
        }
    },
    methods: {
      newChat() {
      },
      renderedMarkdownTest(test) {
            if(test === undefined) {
                return "";
            } 
            return marked("AI："+test);
      },
      selectChat(index) {
        this.currentIndex = index;
      },
      sendMessage() {
        const question = this.newMessage;
        if (this.newMessage.trim() !== "") {
          this.currentChat.messages.push({ userRight: "我：", textRight: this.newMessage,msgType: "right" });
          this.newMessage = "";
        } else {
            return;
        }
        const url = "http://192.168.110.48:9411/htp/sse/sse?userId=1&msg=" + question;
        console.log("url = ",encodeURI(url));
        this.eventSource = new EventSource(encodeURI(url));
        // this.eventSource = new EventSource("https://ks-api.shangboyx.com/ks/sse/postSse?msg=%E8%A6%81%E4%B8%8E%E4%B8%80%E4%BD%8D%E7%BE%8E%E9%A3%9F%E7%B1%BB%E6%8A%96%E9%9F%B3%E8%BE%BE%E4%BA%BA%E5%BB%BA%E8%81%94%EF%BC%8C%E6%88%91%E6%89%93%E6%8B%9B%E5%91%BC%E7%AC%AC%E4%B8%80%E5%8F%A5%E5%9B%A0%E8%AF%A5%E8%AF%B4%E4%BB%80%E4%B9%88");
        
        // 监听服务器消息
        this.eventSource.onmessage = (event) => {
            if("[DONE]" === event.data) {
                return
            }
            this.dsMsg = JSON.parse(event.data)
            if (this.dsMsg === '') {
                return
            }
            let reasoning_content = this.dsMsg.choices[0].delta.reasoning_content
            let content = this.dsMsg.choices[0].delta.content

            // 将新消息添加到 messages 数组
            const length = this.currentChat.messages.length;
            const lastMsg = this.currentChat.messages[length - 1];

            console.log("reasoning_content = ",reasoning_content);

            if (lastMsg.msgType === "right") {
                if(reasoning_content !== "" && reasoning_content !== undefined) {
                    this.currentChat.messages.push({ userLeft:"",
                        textLeft: reasoning_content, 
                        msgType: "left" });
                } else if(content !== "" && content !== undefined) {
                    this.currentChat.messages.push({ userLeft:"",
                        textLeft: content, 
                        msgType: "left" });
                }
            } else {
                if(reasoning_content !== "" && reasoning_content !== undefined) {
                    lastMsg.textLeft += reasoning_content
                } 
                if(content !== "" && content !== undefined ) {
                    lastMsg.textLeft += content
                }
                
            }
        };
  
        // 错误处理
        this.eventSource.onerror = (error) => {
          console.error("SSE Error:", error);
          this.eventSource.close(); // 关闭连接
        };

      }
    }
  };
  </script>
  
<style>
.send-message-div{
    display: flex;
    gap: 12px; /* 元素间距 */
    align-items: center; /* 垂直居中 */
    margin-left: 500px;
    margin-right: 500px;
    margin-top: auto;
}
.chat-list{
    margin-top: 20px;
}
.left-aside {
    background-color: #F9FBFF;
}
.right-main {
    background-color: white;
    display: flex;
    flex-direction: column;  /* 垂直排列 */
    min-height: 100vh;       /* 至少撑满视口高度 */
}
.messag-cent {
    display: flex;
    justify-content: space-between; /* 两端对齐 */
    padding: 12px;
    margin-left: 200px;
    margin-right: 200px;
}
.messag-cent-left{
    display: flex;
    gap: 10px; /* 元素间距 */
}
.messag-cent-right{
    display: flex;
    gap: 1px; /* 元素间距 */
}
.new-chat-btn{
    margin-top: 20px;
}
.msg{    
    /* display: flex; */
    width: 600px;
    text-align: justify; /*实现两端对齐*/
    text-justify: newspaper; /*通过增加或减少字或字母之间的空格对齐文本*/
    word-break: break-all; /*允许在单词内换行*/
    /* white-space: pre-wrap;  */
    /*这个参数根据需要来绝对要不要*/
    /* overflow: hidden; */
}
</style>
  